package com.bdqn.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.demo.dao.MenuDao;
import com.bdqn.demo.pojo.Menu;
import com.bdqn.demo.service.MenuService;
import com.bdqn.demo.utils.ThreadHold;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 后台菜单表(Menu)表服务实现类
 *
 * @author makejava
 * @since 2024-01-16 19:08:21
 */
@Service("menuService")
public class MenuServiceImpl extends ServiceImpl<MenuDao, Menu> implements MenuService {

    @Autowired
    private MenuDao menuDao;

    @Override
    public List<Menu> getMenu() {
        List<Menu> menus = menuDao.getMenu(ThreadHold.get().getId());
        return buildTree(menus);
    }

    private static List<Menu> buildTree(List<Menu> menus) {
        List<Menu> trees = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getParentId() == 0) {
                trees.add(findChildren(menu, menus));
            }
        }
        return trees;
    }

    private static Menu findChildren(Menu menu, List<Menu> treeNodes) {
        menu.setChildren(new ArrayList<>());
        for (Menu treeNode : treeNodes) {
            if (Objects.equals(treeNode.getParentId(), menu.getId())) {
                menu.getChildren().add(findChildren(treeNode, treeNodes));
            }
        }
        return menu;
    }
}

